package com.haikesi.api.resource.controller;

import com.github.pagehelper.PageInfo;
import com.haikesi.api.base.ApiIndex;
import com.haikesi.api.base.Error;
import com.haikesi.api.base.R;
import com.haikesi.api.base.Type;
import com.haikesi.api.resource.domain.vo.ResourecesFlagVO;
import com.haikesi.api.resource.domain.vo.ResourecesSavaVO;
import com.haikesi.api.resource.domain.vo.ResourecesSearchVO;
import com.haikesi.api.resource.domain.vo.ResourecesUpdateVO;
import com.haikesi.api.resource.service.ResoureService;
import com.haikesi.api.user.domain.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: ResourceController
 * @Description: 资源管理的增删改查
 * @author: dx
 * @date: 2019年4月28日 上午11:40:31
 * @version V1.0
 * @Copyright: 2019 重庆海克斯科技有限公司. 注意：本内容仅限于重庆海克斯科技有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
@Api(description = "资源管理相关接口", tags = ApiIndex.ResourceController)
@RequestMapping(value = "/api/resource")
@RestController
public class ResourceController {
	@Autowired
	ResoureService service;

	@ApiOperation(value = "资源列表")
	@GetMapping(value = "/list")
	public R<PageInfo<List<UserVO>>> demoGet(@ModelAttribute ResourecesSearchVO SearchVO) {
		List<ResourecesFlagVO> resourceManage = service.getList(SearchVO);
		PageInfo pageInfo = new PageInfo(resourceManage);
		return new R(pageInfo);
	}

	@ApiOperation(value = "添加资源")
	@PostMapping(value = "")

	public R create(@ApiParam(value = "添加参数") @Valid @RequestBody ResourecesSavaVO vo, BindingResult bindingResult) {
		if(bindingResult.hasErrors()) {
			List<Error> messages=new ArrayList<>();
			for(int i=0;i<bindingResult.getFieldErrors().size();i++){
				messages.add(new Error(bindingResult.getFieldErrors().get(i).getField(),bindingResult.getFieldErrors().get(i).getDefaultMessage()));
			}
			return new R(Type.FORMAT_EXCEPTION).setMessages(messages);
		}
		/*if(){

		}*/
		return new R().setData(service.create(vo));
	}

	@ApiOperation(value = "修改资源")
	@PutMapping(value = "")
	public R update(@ApiParam(value = "修改参数") @Valid @RequestBody ResourecesUpdateVO updateVO, BindingResult bindingResult) {
		if(bindingResult.hasErrors()) {
			List<Error> messages=new ArrayList<>();
			for(int i=0;i<bindingResult.getFieldErrors().size();i++){
				messages.add(new Error(bindingResult.getFieldErrors().get(i).getField(),bindingResult.getFieldErrors().get(i).getDefaultMessage()));
			}
			return new R(Type.FORMAT_EXCEPTION).setMessages(messages);
		}
		service.update(updateVO);
		return new R();
	}

	@ApiOperation(value = "删除资源")
	@DeleteMapping(value = "")
	public R delete(@ApiParam(value = "删除参数") @RequestParam String id) {
		service.deleteResourceById(id);
		return new R();
	}

}
